﻿using System;
using System.Data.Entity;
using System.Data.Entity.Infrastructure;
using System.Data.Entity.ModelConfiguration;
using BPM.Common;
using BPM.Entity;
using BPM.Service.Mappings;
using System.Linq;
using System.Data.Objects;

namespace BPM.Service
{
    /// <summary>
    /// 这里只对测试工程设计为public，方便测试。
    /// </summary>
    public class BarcodeContext : DbContext
    {
        static BarcodeContext()
        {
            Database.SetInitializer(new EntitiesInitializer());
        }

        public BarcodeContext()
            : base("BPM")
        {
            //this.ObjectContext.ContextOptions.LazyLoadingEnabled = false;
            //this.ObjectContext.ContextOptions.UseLegacyPreserveChangesBehavior = true;
            this.ObjectContext.ContextOptions.ProxyCreationEnabled = false;
        }

        protected override void OnModelCreating(ModelBuilder modelBuilder)
        {
            //基于约定添加
            var configTypes = this.GetType().Assembly.GetTypes()
                .Where(t =>
                    t.BaseType.IsGenericType &&
                    t.BaseType.GetGenericTypeDefinition() == typeof(EntityConfiguration<>)
                    );

            foreach (var configType in configTypes)
            {
                var config = Activator.CreateInstance(configType) as StructuralTypeConfiguration;
                modelBuilder.Configurations.Add(config);
            }

            base.OnModelCreating(modelBuilder);
        }

		public ObjectStateManager ObjectStateManager
		{
			get
			{
				return this.ObjectContext.ObjectStateManager;
			}
		}

        public Result Save()
        {
            try
            {
                this.SaveChanges();
                return new Result(true, "保存成功。");
            }
            catch (Exception ex)
            {
                return ex.Message;
            }
        }

        //public void Attach(object entity)
        //{
        //    this.Set<
        //}

        //public void Detect()
        //{
        //    this.ObjectContext.DetectChanges();
        //}
    }
}